﻿//============================================================
//Grid
//============================================================
function Grid() {
    var _this = this;
    _this.ID = ""; //指定ID
    _this.MultSelect = false; //支持多选
    _this.PageSize = 10; //每页显示记录行数
    _this.IsPage = true; //是否分页取数据
    _this.SelectPage = 1; //当前选中页码
    _this.PageConut = 0; //总页数
    _this.RowCount = 0; //记录总行数
    _this.FilterString = ""; //查询条件，以and开头，可以为空
    _this.OrderColumn = ""; //排序字段
    _this.OrderType = "ASC"; //排序类型
    _this.Edit = false; //是否支持在Grid中编辑
    _this.HeadArr = new Array(); //表头属性数组
    _this.ColumnArr = new Array(); //记录行属性数组
    _this.PagePanelID = "";
    _this.vPageIndexName = ""; //是否记录页数,空的话不记录页数
    _this.RowStyleKey = "";
    _this.RowTitleKey = "";
    _this.RowClassKey = "";
    _this.RowAlternate = true;//是否采用交替行样式
    _this.ShowSequence = false;//是否显示行编号
    _this.Height = "400px";//默认Grid高度
    _this.InitFun = null; //外部初始化方法的名称
    _this.AlignCenter = true;//默认横向居中
    _this.FixeHead = true;//默认固定表头

    function pageInit() {
        if (_this.InitFun) {
            _this.InitFun();
        }
    }

    function itemMouseOver(item) {
        $(item).addClass("grid-row-mouseover");
    }

    function itemMouseClick(item) {

    }

    function itemMouseOut(item) {
        $(item).removeClass("grid-row-mouseover");
    }

    function itemHeadClick(columnName) {
        _this.OrderColumn = columnName;
        _this.OrderType = _this.OrderType == "ASC" ? "DESC" : "ASC";
        pageInit();
    }

    function selectPage(obj) {
        _this.SelectPage = eval(obj.value);
        pageInit();
        //记录页数
        if (_this.vPageIndexName != "") {
            setStorage(_this.vPageIndexName, _this.SelectPage);
        }
    }

    function jumpFirstPage() {
        _this.SelectPage = 1;
        pageInit();
        //记录页数
        if (_this.vPageIndexName != "") {
            setStorage(_this.vPageIndexName, _this.SelectPage);
        }
    }

    function jumpLastPage() {
        _this.SelectPage = _this.PageConut;
        if (_this.PageConut == 0)
            return;

        pageInit();
        //记录页数
        if (_this.vPageIndexName != "") {
            setStorage(_this.vPageIndexName, _this.SelectPage);
        }
    }

    function jumpFrontPage() {
        if (_this.SelectPage > 1) {
            _this.SelectPage = eval(_this.SelectPage) - 1;
            pageInit();
        }
        //记录页数
        if (_this.vPageIndexName != "") {
            setStorage(_this.vPageIndexName, _this.SelectPage);
        }
    }

    function jumpNextPage() {
        if (_this.SelectPage < _this.PageConut) {
            _this.SelectPage = eval(_this.SelectPage) + 1;
            pageInit();
        }
        //记录页数
        if (_this.vPageIndexName != "") {
            setStorage(_this.vPageIndexName, _this.SelectPage);
        }
    }

    function initPageControls() {
        var vPage = $("#" + _this.ID).children(".grid-bottom"); //获取grid的bottom

        if (_this.IsPage == false) {
            $(vPage).hide();
            return;
        }
        
        //创建分页下拉框
        var vselpagesize = $("<select title='选择当前页显示记录的行数'><option>10</option><option>15</option><option>20</option><option>25</option><option>30</option></select>").addClass("pagesize").change(
            function () {
                _this.PageSize = eval($(this).val());
                _this.SelectPage = 1; //设置完分页数后默认加载第一页
                pageInit();
            }).val(_this.PageSize);
        //创建翻页按钮和要显示的内容
        var vsf = $("<span/>").addClass("imgbtn first").click(function () {
            jumpFirstPage();
        });
        var vsl = $("<span/>").addClass("imgbtn last").click(function () {
            jumpLastPage();
        });
        var vsn = $("<span/>").addClass("imgbtn next").click(function () {
            jumpNextPage();
        });
        var vsp = $("<span/>").addClass("imgbtn prev").click(function () {
            jumpFrontPage();
        });
        var vtxt1 = $("<span/>").css("margin-left","10px").text("第");
        var vtxt2 = $("<span/>").css("margin-right","10px").text("页，共 " + _this.PageConut + " 页");
        var vpi = $("<input title='敲回车翻页'/>").addClass("pagenum").one("focusin", function () {
            $(this).keydown(function (event) {
                if (event.keyCode == 13) {
                    var vpagenum = $("#" + _this.ID).find(".grid-bottom>.pagenum").val();
                    var re = /^[0-9]*[1-9][0-9]*$/;
                    if (!re.test(vpagenum)) {//判断是否为数字
                        alert("请填写正确的数字！");
                        $("#" + _this.ID).find(".grid-bottom>.pagenum").val(_this.SelectPage); //将页数改为当前页
                        return;
                    }
                    else {//判断是否超过了页数范围
                        if (eval(vpagenum) > _this.PageConut) {
                            alert("超出当前页数的最大值！");
                            $("#" + _this.ID).find(".grid-bottom>.pagenum").val(_this.SelectPage);
                            return;
                        }
                    }
                    _this.SelectPage = eval(vpagenum);
                    pageInit();
                }
            });
        });
        var vlable = $("<label/>").addClass("txt");

        $(vPage).append(vselpagesize).append($("<span class='separator'/>")).append(vsf).append(vsp).append($("<span class='separator'/>")).append(vtxt1).append(vpi).append(vtxt2).append($("<span class='separator'/>")).append(vsn).append(vsl).append($("<span class='separator'/>")).append(vlable);

        if (_this.PagePanelID != "") {//兼容以前的代码，将翻页功能加载到指定位置
            $("#" + _this.PagePanelID).html(vPage);
        }
    }

    function bindSelect() {
        if (_this.IsPage == false)
            return;
        var vgrid = $("#" + _this.ID); 
        $(vgrid).find(".grid-bottom>.pagenum").val(_this.SelectPage);       

        var vFirst = eval((_this.SelectPage - 1) * _this.PageSize + 1);
        var vEnd = eval(_this.SelectPage * _this.PageSize);
        if (vEnd > _this.RowCount)
            vEnd = _this.RowCount;

        var vRowCount = 0;
        if (_this.RowCount != undefined)
            vRowCount = _this.RowCount;

        var vText = "当前显示第" + vFirst + "条到" + vEnd + "条记录，一共" + vRowCount + "条";
        $(vgrid).find(".grid-bottom>.txt").text(vText);
    }

    function initHead() {
        var vTable = $("#" + _this.ID).children(".grid-head").children("table");
        var vTr = $("<tr/>");
        if (_this.ShowSequence) {
            $(vTr).append($("<th/>").append($("<div/>").addClass("grid-Sequence")));
        }

        for (var ii = 0; ii < _this.HeadArr.length; ii++) {
            var obj = eval(_this.HeadArr[ii]);
            var vTh = $("<th/>").attr("align","center");
            var vdiv = $("<div/>")
            if (obj.width != "undefined") {
                $(vdiv).width(obj.width);
            }
            if (obj.colspan) {
                var colspan = obj.colspan;
                $(vTh).attr("colspan", colspan);
            }
            if (obj.text == "选择") {
                var vCk = $("<input id='chbCheckAll' type='checkbox' title='选中/取消选中'/>");
                $(vCk).click(function () {
                    var vTableGrid = $("#" + _this.ID).find(".grid-body>table");
                    if ($(this).prop("checked")) {
                        $(vTableGrid).find(":checkbox").prop("checked", "true");
                    }
                    else {
                        $(vTableGrid).find(":checkbox").removeAttr("checked");
                    }
                });
                $(vdiv).append(vCk);
            }
            else if (obj.orderColumn != null) {
                var vA = $("<a href='#'/>").addClass("headOrder_" + _this.ID).attr("orderColumn", obj.orderColumn).text(obj.text);
                $(vdiv).append(vA);
            }
            else {
                $(vdiv).text(obj.text);
            }
            $(vTh).attr("align", obj.align).append(vdiv);
            $(vTr).append(vTh);
        }
        $(vTable).append(vTr);
    }

    function initBody(DataList) {
        var vTableGrid = $("#" + _this.ID).children(".grid-body").children("table");
        for (var ii = 0; ii < DataList.length; ii++) {
            var rowStyle = "";
            if (_this.RowAlternate) {
                if (ii % 2 == 0) {
                    rowStyle = "grid-row";
                }
                else {
                    rowStyle = "grid-row-alternate";
                }
            }

            if (_this.RowClassKey && _this.RowClassKey.length > 0) {
                rowStyle += " " + (DataList[ii][_this.RowClassKey] || "");
            }

            var rowStyleKeyValue = "";
            var rowTitleKeyValue = "";
            if (_this.RowStyleKey && _this.RowStyleKey.length > 0) {
                rowStyleKeyValue = DataList[ii][_this.RowStyleKey] || "";
            }
            if (_this.RowTitleKey && _this.RowTitleKey.length > 0) {
                rowTitleKeyValue = DataList[ii][_this.RowTitleKey] || "";
            }

            var vTr = $("<tr/>").addClass(rowStyle).attr("trindex", ii).attr("style", rowStyleKeyValue).attr("title", rowTitleKeyValue);
            if (_this.ShowSequence) {
                $(vTr).append($("<td/>").append($("<div/>").html(ii + 1).addClass("grid-Sequence")));
            }

            for (var xx = 0; xx < _this.ColumnArr.length; xx++) {
                var obj = eval(_this.ColumnArr[xx]);
                var vTd = $("<td/>");
                var vdiv = $("<div/>").width(_this.HeadArr[xx].width);
                var vTemp = DataList[ii][obj.name];
                vTemp = (vTemp == null || vTemp == undefined) ? "" : vTemp;
                //var vTemp2 = "";
                if (obj.disLength != null) {
                    if (vTemp.length > obj.disLength) {
                        $(vdiv).attr("title", vTemp);
                        vTemp = vTemp.substr(0, obj.disLength) + "...";
                    }
                }

                if (obj.align != undefined) {
                    $(vTd).attr("align", obj.align);
                }

                if (obj.disabled != undefined) {
                    $(vTd).attr("disabled", obj.disabled);
                }
                var vUrl = "";
                if (obj.url != undefined) {
                    vUrl = DataList[ii][obj.url];
                }

                //disabled
                var vDisabled = "";
                if (obj.disabledKey != undefined && obj.disabledKey != null && obj.disabledKey != "") {
                    if (DataList[ii][obj.disabledKey] == "disabled" || DataList[ii][obj.disabledKey] == "True") {
                        vDisabled = "disabled";
                    }
                } else {
                    vDisabled = "";
                }

                if (obj.Title != undefined && obj.Title != null && obj.Title != "") { 
                }

                switch (obj.columnType) {
                    case "lab":
                        if (_this.Edit == true && obj.edit) {
                            var vSpan = $("<span id='aLable'/>").html(vTemp);
                            var vText = $("<input type='text'>").attr("id", obj.name).addClass("txt_normal").attr("style", "display:none;width:99%").val(DataList[ii][obj.name]);
                            $(vdiv).attr("columnName", obj.name).attr("edit", obj.edit).append(vSpan).append(vText);
                        }
                        else {
                            $(vdiv).html(vTemp);
                        }
                        break;
                    case "btn":
                        if (obj.text != null)
                            vTemp = obj.text;
                        if (obj.name) {
                            vTemp = DataList[ii][obj.name];
                        }

                        var vNodeID = "";
                        if (obj.key != null) {
                            var arrKey = obj.key.split(',');
                            for (var m = 0; m < arrKey.length; m++) {
                                if (arrKey[m] != "") {
                                    vNodeID += DataList[ii][arrKey[m]] + "$";
                                }
                            }
                            if (vNodeID != "")
                                vNodeID = vNodeID.substring(0, vNodeID.length - 1);
                        }

                        if (vDisabled == "") {
                            if (_this.Edit == true && obj.edit) {
                                if (obj.text != null) {
                                    var va1 = $("<a  id='aEdit' href='#' " + vDisabled + "/>").html(vTemp);
                                    var va2 = $("<a id='aSave' href='#' onclick='" + obj.funName + "(this);' style='display:none'/>").attr("key", obj.key).attr("nodeid", vNodeID).text("保存");
                                    var va3 = $("<a id='aCancle' href='#' style='display:none'/>").text("取消");
                                    $(vdiv).append(va1).append(va2).append(va3);
                                }
                                else {
                                    var va3 = $("<a id='aLable' href='#'  onclick='" + obj.funName + "(this);' " + vDisabled + "/>").html(vTemp).attr("nodeid", vNodeID);
                                    var vText = $("<input type='text'>").attr("id", obj.name).addClass("txt_normal").attr("style", "display:none;width:99%").val(DataList[ii][obj.name]);
                                    $(vdiv).attr("columnName", obj.name).attr("edit", obj.edit).append(va3).append(vText);
                                }
                            }
                            else {
                                var va4 = $("<a href='#' onclick='" + obj.funName + "(this);' " + vDisabled + "/>").attr("key", obj.key).attr("nodeid", vNodeID).attr("url", vUrl).html(vTemp);
                                if (obj.name) {
                                    va4 = $("<a href='#' onclick='" + obj.funName + "(this);' " + vDisabled + "/>").attr("key", obj.key).attr("nodeid", vNodeID).attr("url", vUrl).html(vTemp);
                                }

                                $(vdiv).append(va4);
                            }
                        }
                        break;
                    case "img":
                        var vImg = $("<img height='16px' width='16px'/>").attr("src", "../" + DataList[ii][obj.src]);
                        $(vdiv).append(vImg);
                        break;
                    case "imgBtn":
                        if (obj.imgSrc) {
                            var visible = true;
                            if (obj.imgVisibleKey) {
                                visible = DataList[ii][obj.imgVisibleKey];
                            }
                            if (visible) {
                                var vImg = $("<img/>").attr("src", obj.imgSrc).css("cursor", "pointer");

                                vImg.css("height", obj.imgHeight || 16);
                                vImg.css("width", obj.imgHeight || 16);

                                if (obj.key && obj.key != "") {
                                    vImg.attr("data-key", DataList[ii][obj.key]);
                                }
                                if (obj.funName && obj.funName != "") {
                                    vImg.attr("data-oper", obj.funName);                                    
                                }
                                $(vdiv).append(vImg);
                            }
                        }
                        break;
                    case "chb":                       
                        var vCk = $("<input type='checkbox'/>").attr("id", "chb" + ii);
                        if (DataList[ii][obj.name]) {
                            $(vCk).attr("checked", " checked");
                        }

                        $(vCk).attr("nodeid", DataList[ii][obj.key]);
                        if (obj.funName) {
                            $(vCk).attr("onclick", obj.funName + "(this)");
                        }
                        $(vdiv).append(vCk);
                        break;
                    case "btnGroup":
                        var groupCount = obj.group.length;
                        for (var gg = 0; gg < groupCount;gg++)
                        {
                            if (obj.group[gg].disabledKey != undefined && obj.group[gg].disabledKey != null && obj.group[gg].disabledKey != "") {
                                if (DataList[ii][obj.group[gg].disabledKey] == "disabled" || DataList[ii][obj.group[gg].disabledKey] == "True") {
                                    vDisabled = "disabled";
                                }
                            } else {
                                vDisabled = "";
                            }
                            if (vDisabled == "") {
                                if (obj.group[gg].text != null)
                                    vTemp = obj.group[gg].text;
                                if (obj.group[gg].name) {
                                    vTemp = DataList[ii][obj.group[gg].name];
                                }

                                var vNodeID = "";
                                if (obj.group[gg].key != null) {
                                    var arrKey = obj.group[gg].key.split(',');
                                    for (var m = 0; m < arrKey.length; m++) {
                                        if (arrKey[m] != "") {
                                            vNodeID += DataList[ii][arrKey[m]] + "$";
                                        }
                                    }
                                    if (vNodeID != "")
                                        vNodeID = vNodeID.substring(0, vNodeID.length - 1);
                                }

                                var vlink = $("<a href='#' onclick='" + obj.group[gg].funName + "(this);' " + vDisabled + "/>").attr("key", obj.group[gg].key).attr("nodeid", vNodeID).html(vTemp);
                                $(vlink).css("margin-left", "6px");
                                $(vlink).css("margin-right", "6px");
                                $(vdiv).append(vlink);
                            }
                        }
                        break;
                    default:
                        $(vdiv).html(DataList[ii][obj.name]);
                }
                $(vTd).append(vdiv);
                $(vTr).append(vTd);
            }
            $(vTableGrid).append(vTr);
        }
    }

    function itemRowEdit(item) {
        var vtr = $(item).parent("td").parent("tr").children();

        //处理其他可编辑行的状态
        var vTop = $(item).parent("td").parent("tr").parent().children("tr").children();
        $(vTop).children(":text").css("display", "none");
        $(vTop).children("[id='aLable']").css("display", "block");
        $(vTop).children("[id='aEdit']").css("display", "block");
        $(vTop).children("[id='aSave']").css("display", "none");
        $(vTop).children("[id='aCancle']").css("display", "none");

        $(vtr).children("[id='aLable']").css("display", "none");
        $(vtr).children(":text").css("display", "block");

        var vObj = $(item).parent("td").children("a");
        for (var ii = 0; ii < vObj.length; ii++) {
            if ($(vObj[ii]).attr("id") == "aEdit") {
                $(vObj[ii]).css("display", "none");
            }
            else {
                $(vObj[ii]).css("display", "block");
            }
        }
    }

    function itemRowCancle(item) {
        var vtr = $(item).parent("td").parent("tr").children();

        $(vtr).children("[id='aLable']").css("display", "block");
        $(vtr).children(":text").css("display", "none");

        var vObj = $(item).parent("td").children("a");
        for (var ii = 0; ii < vObj.length; ii++) {
            if ($(vObj[ii]).attr("id") == "aEdit") {
                $(vObj[ii]).css("display", "block");
            }
            else {
                $(vObj[ii]).css("display", "none");
            }
        }
    }

    _this.getModel = function () {
        if (_this.IsPage == false)
            _this.PageSize = 0;

        var vModel = { PageSize: _this.PageSize,
            SelectPage: _this.SelectPage,
            FilterString: _this.FilterString,
            OrderColumn: _this.OrderColumn,
            OrderType: _this.OrderType
        };

        return vModel;
    }

    _this.itemRowSave = function (item) {
        var vtr = $(item).parent("td").parent("tr");
        var vString = "{\"" + $(item).attr("key") + "\":\"" + $(item).attr("nodeid") + "\"";
        var vObj = $(vtr).children("[edit='true']");
        for (var ii = 0; ii < vObj.length; ii++) {
            vString += ",\"" + $(vObj[ii]).attr("columnName") + "\":\"" + $(vObj[ii]).children("input").val() + "\"";
        }
        vString += "}";
        return eval("(" + vString + ")");
    }

    _this.initGrid = function (response) {
        showMask();//显示蒙板
        if (_this.ID == "") {
            alert("请设置Grid的ID！");
            return;
        }

        //基于当前情况，替换顶层table标签为div        
        $("#" + _this.ID).replaceWith($("<div id='" + _this.ID + "'/>").addClass("grid"));

        var vgrid = $("#" + _this.ID);

        if (_this.AlignCenter) {
            $(vgrid).css("margin", "0 auto");
        }

        $(vgrid).html('');
        $(vgrid).append($("<div/>").addClass("grid-head").append($("<table/>").attr("cellspacing", "0px").attr("cellpadding", "0px")));
        $(vgrid).append($("<div/>").addClass("grid-body").append($("<table/>").attr("cellspacing", "0px").attr("cellpadding", "0px")));

        $(vgrid).append($("<div/>").addClass("grid-bottom"));
        //获取行数和页数
        _this.RowCount = response.Count;
        _this.PageConut = Math.ceil(_this.RowCount / _this.PageSize);
        //创建grid头
        initHead();

        //设置grid的宽度
        var vgridWidth = $(vgrid).find(".grid-head>table").width();
        $(vgrid).children(".grid-body").css("overflow-y", "hidden");
        //if (_this.IsPage) {
            //设置body的高度
        if (_this.FixeHead) {
            $(vgrid).children(".grid-body").height(_this.Height);
            vgridWidth = eval(vgridWidth) + 20;
            $(vgrid).children(".grid-body").css("overflow-y", "scroll");
        }
        //}
        $(vgrid).width(vgridWidth);

        //创建Body
        if (response.ListResult != undefined) {
            initBody(response.ListResult);
            $("[data-oper]").click(function () {
                var $this = $(this);
                var dataOper = $this.attr("data-oper");
                eval(dataOper + "(this)");
            });
        }
        //创建Bottom
        initPageControls();
        bindSelect();

        //添加排序事件
        $(".headOrder_" + _this.ID).click(function () {
            itemHeadClick($(this).attr("orderColumn"));
        });

        var vbody = $(vgrid).children(".grid-body");

        $(vbody).find("tr").bind('mouseover', function () {
            itemMouseOver(this);
        });

        $(vbody).find("tr").bind('mouseout', function () {
            itemMouseOut(this);
        });

        $(vbody).find("tr").click(function () {
            itemMouseClick(this);
        })

        $(vbody).find("#aEdit").bind('click', function () {
            itemRowEdit(this);
        });

        $(vbody).find("#aCancle").bind('click', function () {
            itemRowCancle(this);
        });

        //添加首页 上一页 下一页 末页是否可用
        if (_this.SelectPage == 1) {
            $("#firstPage_" + _this.ID).attr("disabled", "disabled").unbind("click");
            $("#frontPage_" + _this.ID).attr("disabled", "disabled").unbind("click");
        }
        if (_this.SelectPage == _this.PageConut) {
            $("#nextPage_" + _this.ID).attr("disabled", "disabled").unbind("click");
            $("#lastPage_" + _this.ID).attr("disabled", "disabled").unbind("click");
        }


        hideMask();//处理完成后关闭蒙板
    }
}